import React from 'react';
import {Button, Card, Form, Input, message, Modal, Popconfirm, Select, Table, Tooltip,} from 'antd';

import SearchForm from '../../components/AutoForm/SearchForm';
import EditCell from '../../components/EditTable/EditCell';
import {connect} from 'dva';

const { Option } = Select;
const { TextArea } = Input;

const EditableContext = React.createContext();

@connect(({ line, customer }) => ({
  requiredCols: line.requiredCols,
  customlist: customer.selectListData,
}))
class EditableCell extends React.Component {
  getInput = (dataIndex, record) => {
    const { customlist } = this.props;
    switch (dataIndex) {
      case 'loadingPlace':
        return <TextArea rows={3} />;
      case 'loadoffPlace':
        return <TextArea rows={3} />;
      case 'customerName':
        return (
          <Select
            style={{ width: 140 }}
            showSearch
            filterOption={(input, option) =>
              option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
          >
            {customlist.map(custom => {
              return <Option value={custom.code}>{custom.label}</Option>;
            })}
          </Select>
        );
      default:
        return <Input />;
    }
  };

  renderCell = ({ getFieldDecorator }) => {
    const {
      editing,
      dataIndex,
      title,
      inputType,
      record,
      index,
      children,
      requiredCols,
      selectData,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item style={{ margin: 0, padding: 0 }}>
            {getFieldDecorator(dataIndex, {
              rules: requiredCols[title],
              initialValue: record[dataIndex],
            })(this.getInput(dataIndex, record, selectData))}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };

  render() {
    return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>;
  }
}

@connect(({ line, customer, loading }) => ({
  tableLoading: loading.effects['line/page'],
  priceLoading: loading.effects['line/pricePage'],
  tableData: line.pageList,
  priceDataSource: line.priceDataSource,
  pagination: line.pagination,
  columns: line.columns,
  searchFields: line.searchFields,
  searchValues: line.searchValues,
  editId: line.editId,
  selectionIds: line.selectionIds,
  selectedRows: line.selectedRows,
  customerList: customer.selectListData,
  hasPrice: line.hasPrice,
}))
class EditableTable extends React.Component {

  state = {
    visible: false,
    priceColumns: [{
      title: '项目名称',
      dataIndex: 'customerName',
      width: '150px',
    }, {
      title: '起始地',
      dataIndex: 'lineStart',
      width: '150px',
    },
      {
        title: '目的地',
        dataIndex: 'lineEnd',
        width: '150px',
      },{
        title: '车型',
        dataIndex: 'carType',
        width: '150px',
      },
      {
        title: '限制',
        dataIndex: 'impose',
        width: '150px',
      },
      {
        title: '单位',
        dataIndex: 'imposeUnit',
        width: '150px',
      },
      {
        title: '价格',
        dataIndex: 'price',
        width: '150px',
        editable: true,
      },
    ]
  };

  componentDidMount() {
    const { dispatch } = this.props;
    this.handleSearch();
    dispatch({
      type: 'customer/selectList',
    });
    dispatch({
      type: 'line/hasPrice',
    });
  }
  cancel = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'line/handleEdit',
      payload: '',
    });
  };

  save(form, id, ) {
    const { dispatch, customerList } = this.props;
    form.validateFields((error, row) => {
      if (error) {
        return;
      }
      const { customerName } = row;
      customerList.forEach(customer => {
        if (customer.code === customerName || customer.label === customerName) {
          row.customerName = customer.label;
          row.customerId = customer.code;
        }
      });
      dispatch({
        type: 'line/save',
        payload: { ...row, id },
      }).then(() => {
        this.handleSearch();
      });
    });
  }

  handleEdit(key) {
    const { dispatch } = this.props;
    dispatch({
      type: 'line/handleEdit',
      payload: key,
    });
  }

  handleSearchChange = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'line/handleSearchChange',
      payload: fields,
    });
  };

  handleAdd = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'line/handleAdd',
    });
  };

  handleSearch = (flag) => {
    const { dispatch, pagination, searchValues } = this.props;
    let pageParam = { pageSize: pagination.pageSize, current: flag==='btn' ? 1 : pagination.current  };
    let searchParam = {};
    Object.keys(searchValues).map(key => {
      searchParam[key] = searchValues[key]['value'];
    });
    const param = {
      ...searchParam,
      ...pageParam,
    };
    dispatch({
      type: 'line/page',
      payload: param,
    });
  };

  onChange = (selectedRowKeys, selectedRows) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'line/handleSelection',
      payload: { selectedRowKeys, selectedRows },
    });
  };


  onDel = () => {
    const { dispatch, selectionIds } = this.props;
    if (!selectionIds.length) {
      return message.error('请选择一行要删除的数据');
    }
    dispatch({
      type: 'line/del',
      payload: selectionIds,
    }).then(() => {
      this.handleSearch();
    });
  };

  onPrice = () => {
    const { dispatch, selectionIds } = this.props;
    if (selectionIds.length != 1) {
      return message.error('请选择一行要报价的数据');
    }
    dispatch({
      type: 'line/pricePage',
      payload: {lineId: selectionIds[0]}
    }).then(()=>{
      this.setState({visible: true})
    })
  }

  onCancel = () => {
    this.setState({visible: false})
  }

  savePrice = row => {
    const { dispatch, selectionIds } = this.props;
    dispatch({
      type: 'line/savePrice',
      payload: { ...row },
    }).then(()=>{
      dispatch({
        type: 'line/pricePage',
        payload: {lineId: selectionIds[0]}
      })
    })
  }


  render() {
    const {
      columns,
      pagination,
      tableLoading,
      tableData,
      searchFields,
      searchValues,
      editId,
      dispatch,
      hasPrice,
    } = this.props;
    const components = {
      body: {
        cell: EditableCell,
      },
    };

    const optColumns = columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          inputType: 'text',
          dataIndex: col.dataIndex,
          title: col.title,
          editing: editId === record.id,
        }),
      };
    });
    optColumns.push({
      title: '操作',
      width: '120px',
      fixed: 'right',
      render: (text, record) => {
        const editable = editId === record.id;
        return editable ? (
          <span>
            <EditableContext.Consumer>
              {form => (
                <Tooltip placement="bottom" title="保存">
                  <Button
                    size="small"
                    onClick={() => this.save(form, record.id)}
                    icon="save"
                  />
                </Tooltip>
              )}
            </EditableContext.Consumer>
            <Popconfirm
              title="确认取消?"
              cancelText="取消"
              okText="确定"
              onConfirm={() => this.cancel(record.id)}
            >
              <Tooltip placement="bottom" title="撤回">
                <Button size="small" icon="rollback" />
              </Tooltip>
            </Popconfirm>
          </span>
        ) : (
          <Tooltip placement="bottom" title="编辑">
            <Button
              size="small"
              icon="edit"
              onClick={() => this.handleEdit(record.id)}
            />
          </Tooltip>
        );
      },
    });

    pagination.onChange = (page, pageSize) => {
      let searchParam = {};
      Object.keys(searchValues).map(key => {
        searchParam[key] = searchValues[key]['value'];
      });
      dispatch({
        type: 'line/page',
        payload: {
          ...searchParam,
          current: page,
          pageSize,
        },
      });
    };
    pagination.onShowSizeChange = (current, size) => {
      let searchParam = {};
      Object.keys(searchValues).map(key => {
        searchParam[key] = searchValues[key]['value'];
      });
      dispatch({
        type: 'line/page',
        payload: {
          ...searchParam,
          current: current,
          pageSize: size,
        },
      });
    };

    const rowSelection = {
      type: 'checkbox',
      selections: this.props.selectedRows,
      selectedRowKeys: this.props.selectionIds,
      onChange: this.onChange
    };

    return (
      <Card bodyStyle={{ padding: 0 }}>
        <SearchForm
          header="线路->操作"
          layout="inline"
          moneyText="填写价格"
          onMoney={this.onPrice}
          isAdd={true}
          isDel={true}
          isMoney={hasPrice}
          onFieldsChange={this.handleSearchChange}
          onAdd={this.handleAdd}
          onSubmit={() => {this.handleSearch('btn')}}
          onDel={this.onDel}
          fields={searchFields}
          fieldValue={searchValues}
        />
        <EditableContext.Provider value={this.props.form}>
          <Table
            components={components}
            bordered
            rowKey="id"
            loading={tableLoading}
            dataSource={tableData}
            columns={optColumns}
            rowSelection={rowSelection}
            scroll={{ x: 'max-content' }}
            size="small"
            pagination={pagination}
          />
        </EditableContext.Provider>

        <Modal
          width={800}
          maskClosable={false}
          destroyOnClose
          title="线路价格"
          visible={this.state.visible}
          onCancel={this.onCancel}
          footer={null}
        >
          <EditCell dataSource={this.props.priceDataSource} columns={this.state.priceColumns} loading={this.props.priceLoading} save={this.savePrice}/>
        </Modal>

      </Card>
    );
  }
}
const EditableFormTable = Form.create()(EditableTable);
export default EditableFormTable;
